package com.clouddot.baipai.ui.fragment.H;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerISchoolFragmentComponent;
import com.clouddot.baipai.contract.ISchoolFragmentContract;
import com.clouddot.baipai.http.entity.response.getArcticListResponse;
import com.clouddot.baipai.http.entity.response.getSchoolInfoResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.SchoolFragmentModule;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.adapter.H_schoolTitleAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;
import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.file.FileNameGenerator;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;
import org.wxy.sdk.util.imageloader.ImageLoaderUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;


/**
 * Created by wxy on 2018/8/23.
 * 横版班牌学校的主页面
 */

public class H_SchoolFrgment extends BaseFragment implements ISchoolFragmentContract.IView {
    //存放学校item的列表
    private List<getArcticListResponse.ariticInfo> mDataList = new ArrayList<>();
    //学校列表的适配器
    private H_schoolTitleAdapter H_schoolTitleAdapter;

    private boolean isRunning = false;

    private HttpProxyCacheServer proxy;
    private String videoPath;
    private TxVideoPlayerController controller;

    @Inject
    ISchoolFragmentContract.IPresenter mPresenter;
    @BindView(R.id.leftRecyler)
    RecyclerView leftRecyler;
    @BindView(R.id.LoadingL)
    ImageView LoadingL;
    @BindView(R.id.loadingLF)
    RelativeLayout loadingLF;

    @BindView(R.id.LoadingR)
    ImageView LoadingR;
    @BindView(R.id.loadingLR)
    RelativeLayout loadingLR;

    @BindView(R.id.oneS)
    ScrollView oneS;
    @BindView(R.id.imageOne)
    ImageView imageOne;
    @BindView(R.id.tvOne)
    WebView tvOne;

    @BindView(R.id.VideoView)
    NiceVideoPlayer VideoView;

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_school, null);
    }

    @Override
    protected void initViews() {
        DaggerISchoolFragmentComponent.builder().schoolFragmentModule(new SchoolFragmentModule(this)).build().inject(this);
        mPresenter.getArcticeInfo("SchoolInfo", 1, 10);

    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        LoadingL.startAnimation(loadingAnim);
        LoadingR.startAnimation(loadingAnim);
        controller = new TxVideoPlayerController(getActivity());

    }

    @Override
    protected void loadData() {

    }
    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadingLF.setVisibility(View.VISIBLE);
            leftRecyler.setVisibility(View.GONE);
            loadingLR.setVisibility(View.VISIBLE);
            oneS.setVisibility(View.GONE);
            mPresenter.getArcticeInfo("SchoolInfo", 1, 10);
        } else {
            NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        }
    }


    /**
     *
     * @param flag 1 --> 获取学校item的内容
     *             2 --> 获取学校item的列表
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refluesShcoolInfo(object);
        } else if (flag == 2) {
            refluesArcticeList(object);
        }
        isRunning = false;
    }

    @Override
    public void fail(String errMsg) {
        isRunning = false;
        ToastUtil.showToast(getActivity(), errMsg);
    }


    /**
     *
     * 更新学校item内容
     * @param object
     */
    private void refluesShcoolInfo(Object object) {
        getSchoolInfoResponse response = (getSchoolInfoResponse) object;
        if (response.BaseData.Detail != null && !response.BaseData.Detail.isEmpty()) {
            final String html = EscapeUnescapeUtil.unescape(response.BaseData.Detail);
            tvOne.setBackgroundColor(0);
            tvOne.getSettings().setDefaultTextEncodingName("UTF -8");
            tvOne.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
            tvOne.setVisibility(View.VISIBLE);
        } else {
            tvOne.setVisibility(View.GONE);
        }
        if (response.VideoData == null || response.VideoData.isEmpty() || response.VideoData.get(0).RealPathName.isEmpty()) {
            VideoView.setVisibility(View.GONE);
        } else {
            videoPath = response.VideoData.get(0).RealPathName;
            String url = "http://" + Env.getAppContext().IP + response.VideoData.get(0).RealPathName;
            String proxyUrl = getProxy().getProxyUrl(url);
            VideoView.setPlayerType(NiceVideoPlayer.TYPE_IJK); // or NiceVideoPlayer.TYPE_NATIVE
            VideoView.setUp(proxyUrl, null);
            controller.setTitle(url);
            VideoView.setController(controller);
            VideoView.setVisibility(View.VISIBLE);

        }
        if (response.ThumbnailData == null || response.ThumbnailData.isEmpty() || response.ThumbnailData.get(0).RealPathName.isEmpty()) {
            imageOne.setVisibility(View.GONE);
        } else {
            imageOne.setVisibility(View.VISIBLE);
            ImageLoaderUtil.getInstance().loadImage("http://" + Env.getAppContext().IP + response.ThumbnailData.get(0).RealPathName, imageOne);
        }
        loadingLR.setVisibility(View.GONE);
        oneS.setVisibility(View.VISIBLE);
    }

    /**
     * 更新学校item列表数据
     * @param object
     */
    private void refluesArcticeList(Object object) {
        final getArcticListResponse response = (getArcticListResponse) object;
        if (response.EntityList.isEmpty()) return;
        mDataList = response.EntityList;
        mDataList.get(0).flag = true;
        H_schoolTitleAdapter = new H_schoolTitleAdapter(getActivity(), mDataList);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        leftRecyler.setLayoutManager(mLayoutManager);
        leftRecyler.setItemAnimator(new DefaultItemAnimator());
        H_schoolTitleAdapter.setOnClickListener(new H_schoolTitleAdapter.AdapterItemClickListener() {
            @Override
            public void onClicked(int position) {
                H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                if (!isRunning) {
                    isRunning = true;
                    NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
                    for (getArcticListResponse.ariticInfo ariticInfo : mDataList) {
                        ariticInfo.flag = false;
                    }
                    mDataList.get(position).flag = true;
                    H_schoolTitleAdapter.notifyDataSetChanged();
                    loadingLR.setVisibility(View.VISIBLE);
                    oneS.setVisibility(View.GONE);
                    mPresenter.getScholInfo(mDataList.get(position).Title);
                }
            }

        });
        leftRecyler.setAdapter(H_schoolTitleAdapter);
        loadingLF.setVisibility(View.GONE);
        leftRecyler.setVisibility(View.VISIBLE);
        mPresenter.getScholInfo(mDataList.get(0).Title);
    }

    public HttpProxyCacheServer getProxy() {
        return proxy == null ? (proxy = newProxy()) : proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(getActivity())
                .maxCacheSize(1024 * 1024 * 1024)
                .fileNameGenerator(new MyFileNameGenerator())
                .build();
    }

    public class MyFileNameGenerator implements FileNameGenerator {
        public String generate(String url) {
            return "/BanPai" + videoPath;
        }
    }

}
